# -*- coding: utf-8 -*-
import numpy as np
import gauge


def Tool_SelectRainfallEvent(dat):
    gauge_data = gauge.Read(dat, 229)
    subset2008 = gauge_data[gauge_data.index == 2008]
    subset2008 = gauge.Clean(subset2008)

    rainfallIndex = SelectRainfallEvent(subset2008)

    rainingTimeIndex = ConvertIndexToTime(rainfallIndex, subset2008)
    rainingTimeSeq = ConvertIndexToTimeSeq(rainfallIndex, subset2008)

    rainfallTimeSeq = np.fromiter(rainingTimeSeq, 'S19')

    gauge.Write(r"F:/Research/ProcessResult/rainfallEvents/",
                r"rainfallIndex", rainfallIndex, 0)
    gauge.Write(r"F:/Research/ProcessResult/rainfallEvents/",
                r"rainingTimeIndex", rainingTimeIndex, 3)
    gauge.Write(r"F:/Research/ProcessResult/rainfallEvents/",
                r"rainfallTimeSeq", rainfallTimeSeq, 4)


def SelectRainfallEvent(gaugeData):
    '''select rainfall event from gauge data'''
    EventTime = [[]]
    del EventTime[0]
    startCol = 6
    Tol_Mean_Rainfall = 0.2
    Tol_Event_Time = 6
    Tol_AccRain = 100
    Tol_Suspend_Time = 2

    totalTime = gaugeData.shape[0]
    isStart = 1
    startIndex = 0
    endIndex = 0
    acc_group_num = 0
    acc_events_num = 0
    acc_rainfall = 0
    cur_suspend_time = 0

    for i in range(totalTime):
        # get the current row of gauge data
        # and calculate the mean and sum of the row
        curGaugeData = gaugeData.iloc[i]
        curMeanRain = np.mean(curGaugeData[startCol:])
        curSumRain = np.sum(curGaugeData[startCol:])

        # whether it is a rainfall event or not according to its mean
        if curMeanRain >= Tol_Mean_Rainfall:
            #         restart the suspend time
            cur_suspend_time = 0
            if isStart == 1:
                startIndex = i
                isStart = 0

            acc_events_num += 1
            acc_rainfall += curSumRain
        else:
            #             allow suspend some days
            if cur_suspend_time < Tol_Suspend_Time:
                cur_suspend_time += 1
                continue

            isStart = 1

        # whether it is a group of rainfall events according to the accumulative
        # number of rainfall events
            if acc_events_num >= Tol_Event_Time:
                endIndex = i - cur_suspend_time
                if acc_rainfall >= Tol_AccRain:
                    acc_group_num += 1
                    EventTime.append([startIndex, endIndex])

            acc_rainfall = 0
            acc_events_num = 0

    return EventTime


def ConvertIndexToTimeSeq(index, gaugeData):
    '''Convert the time between start index and end index to time like YYYY-mm-dd_HH:MM:SS'''
    rainfallEvent = []
    for events in index:
        for event in range(events[0], events[1]):
            rainingTime = str(int(gaugeData.iloc[event, 0])) + '-' + str(int(gaugeData.iloc[event, 1])) + '-' + str(int(gaugeData.iloc[event, 2])) + '_' + str(
                int(gaugeData.iloc[event, 3])) + ':' + str(int(gaugeData.iloc[event, 4])) + ':' + str(int(gaugeData.iloc[event, 5]))
            rainfallEvent.append(rainingTime)

    return rainfallEvent


def ConvertIndexToTime(index, gaugeData):
    '''Convert the time between start index and end index to time like YYYY-mm-dd_HH:MM:SS'''
    rainingTimeIndex = [[]]
    del rainingTimeIndex[0]
    for events in index:
        rainingstart = str(int(gaugeData.iloc[events[0], 0])) + '-' + str(int(gaugeData.iloc[events[0], 1])) + '-' + str(int(gaugeData.iloc[events[0], 2])) + '_' + str(
            int(gaugeData.iloc[events[0], 3])) + ':' + str(int(gaugeData.iloc[events[0], 4])) + ':' + str(int(gaugeData.iloc[events[0], 5]))
        rainingend = str(int(gaugeData.iloc[events[1], 0])) + '-' + str(int(gaugeData.iloc[events[1], 1])) + '-' + str(int(gaugeData.iloc[events[1], 2])) + '_' + str(
            int(gaugeData.iloc[events[1], 3])) + ':' + str(int(gaugeData.iloc[events[1], 4])) + ':' + str(int(gaugeData.iloc[events[1], 5]))
        rainingTimeIndex.append([rainingstart, rainingend])

    return rainingTimeIndex


if __name__ == "__main__":
    Tool_SelectRainfallEvent(r"F:/Research/Data/Gauge229_07_10_1h.dat")
